var webpack = require('webpack');
var fs = require('fs');
var config = require('./webpack.dist.config');
var crypto = require("crypto");


const compiler = webpack(config);
// fs.unlink(__dirname + '/dist/*', function (err) {
//     if (err !== null) {
//         console.log(err)
//         return
//     }
//     console.log('删除dist');
// });
console.log('删除dist');
var path = __dirname + '/dist/';
var arr = fs.readdirSync(path);
for(var i = 0, el ; el = arr[i++];){
    var stat = fs.statSync(path+"/"+el);
    if(stat.isFile()){
        //直接删除文件
        fs.unlinkSync(path+"/"+el);
    }
}

console.log('开始打包');
compiler.plugin("compilation", function(compilation) {
    compilation.plugin('optimize-module-ids', function(modules) {
        var contextIndex = 100;
        if (modules.length <= 10) {
            return;
        }
        modules.forEach(function (module) {
            //chunks have circular references to their modules
            if (module.chunks.length === 0 || module.id === 0) {
                return;
            }
            if (module.request) {
                var request = module.request;
                while(request!=request.replace(__dirname, '')) {
                    request=request.replace(__dirname, '');
                }
                request = request.replace(/\\/g, '/').replace(/data-v-[a-z0-9]+/, 'data-v-')
                var sha1 = crypto.createHash('sha1');
                sha1.update(request)
                module.id = sha1.digest('hex').substr(0, 8)
            } else if (module.contextDependencies) {
                console.log(module.contextDependencies);
                module.id = contextIndex++;
            }
        });
    });
    compilation.plugin('optimize-chunk-order', function(chunks) {
        chunks.sort(function(chunk1,chunk2) {
            var sort = {
                'main-base': 100,
                'main-common': 90,
                'main': 1,
                null: 0,
            }
            return sort[chunk2.name] - sort[chunk1.name]
        })
    });
});

compiler.run(function (err, stats) {
    if (err !== null) {
        console.log(err)
        return
    }

    var assets = stats.toJson().assets;

    var main, mainCommon, mainCss, mainCommonCss
    for (var i = 0; i < assets.length; i++) {
        var name = assets[i].name;
        if (name.startsWith('common')) {
            if(name.endsWith('.js')) {
                mainCommon = name;
            } else if(name.endsWith('.css')) {
                mainCommonCss = name;
            }
        } else if (name.startsWith('main')) {
            if(name.endsWith('.js')) {
                main = name;
            } else if(name.endsWith('.css')) {
                mainCss = name;
            }
        }
    }

    fs.readFile(__dirname + '/index.html', function(err, data) {
        if (err) {
            return console.error(err);
        }
        content = data.toString();
        content = content.replace(
            /<script src="\/dist\/[A-Za-z0-9.\-#$%]*" id="common"(.*)><\/script>/,
            '<script src="\/dist\/' + mainCommon + '" id="common"$1><\/script>');
        content = content.replace(
            /<script src="\/dist\/[A-Za-z0-9.\-#$%]*" id="main"(.*)><\/script>/,
            '<script src="\/dist\/' + main + '" id="main"$1><\/script>');
        content = content.replace(
            /<link rel="stylesheet" href="\/dist\/[A-Za-z0-9.\-#$%]*" id="common-css"(.*)>/,
            '<link rel="stylesheet" href="/dist/' + mainCommonCss + '" id="common-css"$1>');
        content = content.replace(
            /<link rel="stylesheet" href="\/dist\/[A-Za-z0-9.\-#$%]*" id="main-css"(.*)>/,
            '<link rel="stylesheet" href="/dist/' + mainCss + '" id="main-css"$1>');
        // console.log(content)
        fs.writeFile(__dirname + '/index.html', content, function(err) {
            if (err) {
                console.log(err)
            }
        })
    });
})